package java4_6.Homework5;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @author oldliu
 * @since 1.0
 */
public class SocketThread extends Thread {
    private final Socket s;

    public SocketThread(Socket s){
        this.s=s;
    }

    @Override
    public void run() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Calendar c =  Calendar.getInstance();
        System.out.println(s+"连接了");
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();

            BufferedReader br=new BufferedReader(new InputStreamReader(in));
            PrintWriter pw=new PrintWriter(out,true);
            while (true){
                String ask=br.readLine();
                if(ask==null||ask.length()==0)
                    continue;
                System.out.println("客户端："+s.getInetAddress()+"问："+ask);
                if (ask.equals("气温")){
                    pw.println(ask+"是20°C"+format.format(c.getTime()));
                }

                if(ask.equals("quit"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
